package servlet;

import service.UserService;

import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.WebServlet;

@WebServlet("/LoginServlet")
public class LoginServlet extends ServletBase {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
                          throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        boolean loginRequired = true;
        if (username == null || password == null || username.isEmpty() || password.isEmpty())
            loginRequired = false;

        if (userService.conn == null) {
            userService.getConnection();
        }

        if (loginRequired && userService.userLogin(username, password)) {

            Cookie[] cookies = request.getCookies();
            int count = 1;
            if (cookies != null) {
                for (Cookie cook : cookies) {
                    if (cook.getName().equals(username)) count = Integer.parseInt(cook.getValue()) + 1;
                }
            }
            Cookie userCookie = new Cookie(username, Integer.toString(count));
            response.addCookie(userCookie);

            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            session.setAttribute("user_acccess_time", count);

            request.getRequestDispatcher("/web/main.jsp").forward(request, response);
            return;
        }

        request.setAttribute("msg", "Invalid username or password!");
        request.getRequestDispatcher("/web/login.jsp").include(request, response);
    }
}
